<?php

if ( !function_exists( 'get_transient' ) ) {

    // for test without WordPress
    function get_transient()
    {
        return false;
    }

    function set_transient()
    {
        return false;
    }

}

class Rsj_iTunes
{
    protected static $cacheExpire = 86400; // = 60*60*24;

    public function __construct()
    {
    }

    public static $iTunesHttpHost = 'http://itunes.apple.com/';

    /**
     * ask Apple the information of app
     *
     * cf. http://www.apple.com/itunes/affiliates/resources/documentation/itunes-store-web-service-search-api.html
     *
     * @assert ('443904275', 'jp') != null
     * @assert ('395228393', 'jp') throws Rsj_EmbedIphoneIpadAppException
     * @return false if failed to fetch the info
     * @exception iPhoneAppEmbedderException
     */
    public static function getAppInfo( $id, $country = null )
    {
        $apiOptions = array(
            'id' => $id
        );
        if ( !is_null( $country ) ) {
            $apiOptions['country'] = $country;
        }

        $cache_key = 'eai_' . $id . '_' . $country;
        $value = get_transient( $cache_key );
        if ($value !== false) {
            echo "<!--$cache_key-->";

            return $value;
        }

        global $wp_version;
        $response = wp_remote_request(
                self::$iTunesHttpHost
                . 'lookup?' . http_build_query( $apiOptions ), array(
            'user-agent' => 'WordPress' . '/' . $wp_version,
            'timeout' => 15,
                )
        );
        if ( is_wp_error( $response ) ) {
            throw new Rsj_EmbedIphoneIpadAppException(
                    __( 'Could not fetch the App information', Rsj_EmbedIphoneIpadApp::PLUGIN_KEY ), 503
            );
        }

        $decodedJson = json_decode( $response['body'], true );
        if (!is_array($decodedJson)
                || !array_key_exists('resultCount', $decodedJson)
                || $decodedJson['resultCount'] == 0
                || !array_key_exists( 'results', $decodedJson )
                || (count( $decodedJson['results'] ) === 0) ) {
            throw new Rsj_EmbedIphoneIpadAppException(
                    __( 'No such application found. Maybe deleted?', Rsj_EmbedIphoneIpadApp::PLUGIN_KEY ), 404
            );
        }

        $gottenAppInfo = $decodedJson['results'][0];
        set_transient( $cache_key, $gottenAppInfo, self::$cacheExpire );

        return $gottenAppInfo;
    }

    /**
     * generate normalized iTunes store URL
     *
     * @assert ('123', null, array('mt' => '8')) === 'http://itunes.apple.com/app/id123?mt=8'
     * @assert ('45678', 'us', array('mt' => '8')) === 'http://itunes.apple.com/us/app/id45678?mt=8'
     */
    public static function getCleanUrl( $id, $country = null, $options = array( 'mt' => '8' ) )
    {
        $paramString = '';
        if ( count( $options ) > 0 ) {
            $paramString = '?' . http_build_query( $options );
        }
        $countryString = (empty( $country ) ? '' : ($country . "/"));

        return self::$iTunesHttpHost . $countryString . 'app/id' . $id . $paramString;
    }

}
